package com.mj.service.system;

import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;






import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.mj.dao.system.UserMapper;
import com.mj.model.system.User;
import com.mj.util.ExportExcel;
import com.mj.util.ImportExcel;
import com.mj.util.PasswordHelper;
@Service("userService")
public class UserServiceImpl implements UserService {

	@Resource
	private UserMapper userDao;
	@Resource
    private PasswordHelper passwordHelper;
	@Override
	public User findById(Integer userId) {
		return this.userDao.selectByPrimaryKey(userId);
	}

	@Override
	public User selectByName(String uname) {
		return this.userDao.selectByUserName(uname);
	}

	@Override 
	public List<Map<String,Object>> findall(Map<String,Object> map) {
		//页面显示记录数
		int pageSize = Integer.parseInt(map.get("rows").toString());
		//起始位置条数
		int offset = Integer.parseInt(map.get("page").toString());
		map.put("notIn", (offset-1)*pageSize);
		map.put("end", pageSize);
		map.put("startDate", map.get("startDate"));//开始日期
		map.put("endDate", map.get("endDate"));
		map.put("userName", map.get("userName"));
		map.put("mobileNum", map.get("mobileNum"));
		map.put("sort", map.get("sort"));
		map.put("order", map.get("order"));
		return this.userDao.findAllUser(map);
	}

	@Override
	public int countUser(Map<String,Object> map) {
		//页面显示记录数
		int pageSize = Integer.parseInt(map.get("rows").toString());
		//起始位置条数
		int offset = Integer.parseInt(map.get("page").toString());
		map.put("start", offset);
		map.put("end", pageSize);
		map.put("startDate", map.get("startDate"));
		map.put("endDate", map.get("endDate"));
		map.put("userName", map.get("userName"));
		map.put("mobileNum", map.get("mobileNum"));
		map.put("sort", map.get("sort"));
		map.put("order", map.get("order"));
		return this.userDao.countUser(map);
	}
	
	@Override
	public int addUser(User u) {
		u.setLatestLoginTime(null);
		u.setRegisterTime(new Timestamp(new Date().getTime()));
		u.setStatus("1");
		//加密密码
        passwordHelper.encryptPassword(u);
		return this.userDao.insertSelective(u);
	}

	@Override
	public int deleteById(Integer id) {
		return this.userDao.deleteByPrimaryKey(id);
	}

	@Override
	public int updateById(User user) {
		//加密密码
        //passwordHelper.encryptPassword(user);
		return this.userDao.updateByPrimaryKeySelective(user);
	}

	@Override
	public int setUserStatus(Integer status,Integer uid) {
		return this.userDao.lockUserStatus(status,uid);
	}

	@Override
	public User selectIdAndName(Integer id, String uname) {
		return this.userDao.selectByIdAndName(id, uname);
	}

	@Override
	public int deleteUserByRoleId(Integer roleid) {
		return this.userDao.deleteByRoleId(roleid);
	}

	@Override
	public User selectByStudentId(String studentId) {
		return userDao.selectByStudentId(studentId);
	}

	@Override
	public User login_user(String name_num_tel) {
		return this.userDao.userToLogin(name_num_tel);
	}

	@Override
	public Integer selectByM_N_S(String name,String num,String tel) {
		return this.userDao.selectByMobile_Name_Stu(name,num,tel);
	}


	@Override
	public List<User> selectUserList() {
		return this.userDao.selectUserList();
	}

	@Override
	public void insertBatchExcel(List<User> ulist) {
		this.userDao.insertBatch(ulist);
	}

	@Override
	public boolean importUserData(MultipartFile file) {
		List<String> columns = new ArrayList<String>();
		columns.add("username");//用户名
		columns.add("name");//真实姓名
		columns.add("student_id");//学号
		columns.add("mobile_number");//手机号
		columns.add("email");//email
		ImportExcel.setColumns(columns);
		boolean success = false;
		//返回的json形式字符串
		try {
			String retJson = ImportExcel.readExcel(file); 
			JSONArray arr =  JSONArray.fromObject(retJson);
			//批量插入，user存放到list中
			List<User> ulist = new ArrayList<User>();
			//i从1开始，（不循环列头信息）
			for(int i = 1;i<arr.size();i++){
				 JSONObject job = arr.getJSONObject(i);
				//是否存在，否即插入
				 int isu = userDao.selectByMobile_Name_Stu(job.getString("username"), null, null);
				 int isNum = userDao.selectByMobile_Name_Stu(null, job.getString("student_id"), null);
				 int isTel = userDao.selectByMobile_Name_Stu(null, null, job.getString("mobile_number"));
				 if(isu == 0 && isNum == 0 && isTel == 0){
					 User user = new User();
					 user.setUsername(job.getString("username"));
	                 user.setName(job.getString("name"));
	                 user.setMobileNumber(job.getString("mobile_number"));
	                 user.setEmail(job.getString("email"));
	                 user.setComment("无");
					 user.setStatus("1");
					 user.setLatestLoginTime(null);
					 user.setRegisterTime(new Timestamp(new Date().getTime()));
					 user.setRoleId(2);//学生
					//加密密码
				     passwordHelper.encryptPassword(user);
					 ulist.add(user);
				 }
//				 else{
//					 size ++;
//				 }
			}
			if(ulist.size()>0){
				userDao.insertBatch(ulist);
			}
			success = true;
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			success = false;
		}
		return success;
	}

	@Override
	public void exportUserData(OutputStream out) {
        //导出数据标题
        String title = "用户信息表格";
        //指定列名
        String[] rowsName = new String[]{"序号","用户名","真实姓名","手机号","邮件","注册时间","最后登录时间","状态","角色类型","备注"};  
	    List<Object[]>  dataList = new ArrayList<Object[]>();
	    //用户列表
	    List<User> ulist = userDao.selectUserList();
	    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	    Object[] objs = null;
	    for (User u:ulist) {  
	        objs = new Object[rowsName.length];  
	        objs[1] = u.getUsername();  
	        objs[2] = u.getName();  
	        objs[3] = u.getMobileNumber();  
	        objs[4] = u.getEmail();  
	        objs[5] = df.format(u.getRegisterTime()) ;
	        if(u.getLatestLoginTime() == null){
	        	objs[6] = "--";
	        }else{
	        	objs[6] =  u.getLatestLoginTime();
	        }
	        objs[7] = Integer.parseInt(u.getStatus()) == 1?"正常":"冻结";  
	        objs[8] = u.getRoleId();
	        objs[9] = u.getComment();
	        dataList.add(objs);  
	    }  
        ExportExcel ex = new ExportExcel(title, rowsName, dataList);
        try {
			ex.export(out);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public int delUserById(String[] ids) {
		return this.userDao.delUserByIds(ids);
	}

	@Override
	public String updatePass(Map<String,Object> map) {
		User user = (User) map.get("user");
        // 新密码
        String newPwd = map.get("newpass").toString();
        // 当前密码
        String currpass = map.get("currpass").toString();
        // 密码盐设为当前用户的值，
        user.setSalt(user.getSalt());
        // 用加密的方法+固定的密码盐salt进行匹配。如果一致，表示密码相同
        String newPassword =
            new SimpleHash(passwordHelper.algorithmName, currpass, ByteSource.Util.bytes(user.getCredentialsSalt()),
                passwordHelper.hashIterations).toHex();
        String flag = "";
        if (!newPassword.equals(user.getPassword())){
            flag = "1";// 新密码错误
        }else{
            User cuser = new User();
            cuser.setUserId(user.getUserId());
            cuser.setPassword(newPwd);
            cuser.setUsername(user.getUsername());
            // 根据用户id，密码，用户名，重新进行密码加密
            passwordHelper.encryptPassword(cuser);
            try {
            	int record =  userDao.updateByPrimaryKeySelective(cuser);
            	if(record > 0){
            		flag = "0";
            	}
			} catch (Exception e) {
				flag = "2";
				e.printStackTrace();
			}
           
        }
		return flag;
	}

	@Override
	public List<User> findAll() {
		return userDao.findAll();
	}

	@Override
	public boolean resetPWD(int uid) {
		User u = new User();
		u.setUserId(Long.valueOf(uid));
		User user = userDao.selectByPrimaryKey(uid);
		u.setUsername(user.getUsername());
		//加密密码
        passwordHelper.encryptPassword(u);
        int tip = userDao.updateByPrimaryKeySelective(u);
        if(tip > 0){
        	return true;
        }else{
        	return false;
        }
	}

	


}
